package com.xk.androiddemo.ui.datashow;

import androidx.lifecycle.ViewModelProvider;

import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.xk.androiddemo.databinding.FragmentDataBinding;


import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class DataFragment extends Fragment {

    private DataViewModel mViewModel;
    private FragmentDataBinding bing;

    public static DataFragment newInstance() {
        return new DataFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        bing = FragmentDataBinding.inflate(getLayoutInflater());
        return bing.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(DataViewModel.class);
        create();
        generatePieData();
        setPieData(bing.pieChart);
        getListData(bing.lineChart);
        bing.rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                create();
                generatePieData();
                setPieData(bing.pieChart);
                getListData(bing.lineChart);
            }
        });
    }
    List<Entry> entries = new ArrayList<>();
    private  void create(){
        entries.clear();
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            float x = i;
            float y = random.nextFloat() * 100;
            entries.add(new Entry(x, y));
        }
    }
    ArrayList<PieEntry> entries2 = new ArrayList<>();
    private void generatePieData(){
        entries2.clear();
        Random random = new Random();
        int numSegments = 3;
        float total = 0;
        float[] percentages = new float[numSegments];
        for (int i = 0; i < numSegments - 1; i++) {
            // 为前n-1个扇区随机分配一个百分比（留有一定余量给最后一个扇区）
            float percentage = random.nextFloat() * (100 - total - (numSegments - i));
            percentages[i] = percentage;
            total += percentage;
        }
        percentages[numSegments - 1] = 100 - total;
        entries2.add(new PieEntry(percentages[0], "正常"));
        entries2.add(new PieEntry(percentages[1], "警报"));
        entries2.add(new PieEntry(percentages[2], "异常"));
    }

    private void getListData(LineChart chart){
// ... 可以根据需要继续添加数据点
// 创建一个LineDataSet实例，并传入数据点列表和数据集标签
        LineDataSet dataSet = new LineDataSet(entries, "数据集标签");
// 设置数据集的样式和属性
        dataSet.setColor(Color.BLUE); // 线条颜色
        dataSet.setLineWidth(2f); // 线条宽度
        dataSet.setCircleColor(Color.BLUE); // 数据点的颜色
        dataSet.setCircleRadius(3f); // 数据点的半径
        dataSet.setDrawCircleHole(false); // 是否绘制数据点中心的空心圆
        dataSet.setValueTextSize(10f); // 数据点值的字体大小
        dataSet.setValueTextColor(Color.BLACK); // 数据点值的字体颜色
        dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); // 设置线条为平滑的贝塞尔曲线
// 可选：设置填充颜色，表示折线下方的填充区域
        dataSet.setFillAlpha(110); // 填充颜色的透明度
        dataSet.setFillColor(ColorTemplate.getHoloBlue()); // 填充颜色
        dataSet.setDrawFilled(true); // 是否绘制填充区域
// 设置数据点标签的格式（例如，显示为整数）
        dataSet.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return String.valueOf((int) value);
            }
        });
        LineData data = new LineData(dataSet);
        chart.setData(data);
        chart.invalidate(); // 刷新图表
        chart.setDescription(null); // 设置图表描述（可选）
        chart.setNoDataText("无数据");
        chart.setNoDataTextColor(Color.BLACK);
        chart.setDrawGridBackground(false);
        chart.setDragEnabled(true); // 允许拖动
        chart.setScaleEnabled(true); // 允许缩放
        chart.setPinchZoom(false); // 禁止双指缩放
        chart.getAxisLeft().setEnabled(false); // 隐藏左侧Y轴
        chart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM); // 设置X轴位置
        chart.getXAxis().setDrawGridLines(false);
    }

    private void setPieData(PieChart pieChart) {
        pieChart.clear();
        int[] MATERIAL_COLORS = {
                Color.rgb(200, 172, 255)
        };
        ArrayList<Integer> colors = new ArrayList<Integer>();
        PieDataSet dataSet = new PieDataSet(entries2, "");
        for (int c : MATERIAL_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.VORDIPLOM_COLORS) {
            colors.add(c);
        }
        dataSet.setColors(colors);
        Description description = new Description();
        description.setEnabled(false);
        dataSet.setValueTextSize(8f); // 设置数值文字大小
        PieData data = new PieData(dataSet);
        data.setDrawValues(false);
        data.setValueFormatter(new PercentFormatter());
        pieChart.setData(data);
        pieChart.setDescription(description);
        pieChart.invalidate(); // 刷新图表
    }

}